
const db = require('db');
const path = require('path');
const evaluate = require('tools/evaluate');
const process = require("child_process");
const log = require("tools/log");
// const { decode } = require('js-base64');

module.exports = async ctx => {
    const { connection, run, comply } = db.init();
    await run('BEGIN'); // 开始事务
    try {
        const id = ctx.params.id;
        const orders = await getOrders(id, run);
        const settlement = await getSettlement(id, comply);
        await deleteSettlementEntry(id, run);
        await deleteSettlement(id, run);
        await updateOrders(id, orders, comply);
        await setOrderAmount(orders, comply);
        // await deleteSettlementDetails(settlement);
        await run('COMMIT');
        ctx.status = 200;
        ctx.body = 'ok';
    } catch (error) {
        await run('ROLLBACK');
        ctx.status = 500;
        ctx.body = error;
        log('---------------------------------------------------')
        console.log(error)
    }
    connection.end();
}

/** 获取订单 */
async function getOrders(id, run) {
    const sqlStr = `
    SELECT o.*, s.unsettlementAmount
    FROM settlementEntry as s
    LEFT JOIN orders AS o ON s.ordersId = o.id
    WHERE s.settlementId = ${id}
    `

    const result = await run(sqlStr);
    if (result.err) {
        throw result.err
    }

    return result.rows;
}

/** 获取结算单 */
async function getSettlement(id, comply) {
    const result = await comply(`
        SELECT *
        FROM settlement
        WHERE id = ${id}
    `);

    return result[0];
}

/** 更新订单数据 */
async function updateOrders(id, orders, comply) {
    for (let i = 0; i < orders.length; i++) {

        const it = orders[i];
        const result = await comply(`SELECT * FROM settlementEntry WHERE ordersId=${it.id}`);

        let total = 0;
        result.forEach(e => {
            if (e.settlementId) {
                total += e.unsettlementAmount
            }
        })

        if (result.filter(e => !e.settlementId).length > 0) {
            await comply(`
                UPDATE settlementEntry 
                SET unsettlementAmount=${evaluate(`${it.businessDay}*${it.price}-${total}`)} 
                WHERE ordersId=${it.id} and settlementId is Null
            `)
        } else {
            await comply(`INSERT INTO settlementEntry ${toInsert({
                ordersId: it.id,
                unsettlementAmount: evaluate(`${it.businessDay}*${it.price}-${total}`)
            })}`)
        }
    }
}

/** 更新订单的结算金额 */
async function setOrderAmount(orders, comply) {
    orders.forEach(async e => {
        const total = (await comply(`SELECT SUM(unsettlementAmount) as total FROM settlementEntry WHERE settlementId IS NOT NULL AND ordersId = ${e.id}`))[0].total;
        await comply(`UPDATE orders SET settlementAmount=${total} WHERE id=${e.id}`)
    })
}

/** 删除 结算单 */
async function deleteSettlement(id, run) {
    const sql = `
        DELETE FROM settlement 
        WHERE id=${id}
    `

    const result = await run(sql);
    if (result.err) {
        throw result.err
    }
}

/** 删除 结算条目 */
async function deleteSettlementEntry(id, run) {
    const sql = `
        DELETE FROM settlementEntry 
        WHERE settlementId=${id}
    `

    const result = await run(sql);
    if (result.err) {
        throw result.err
    }
}

/** 删除结算明细文件 */
// async function deleteSettlementDetails(settlement) {
//     try {
//         if (!settlement.settlementDetails) return;
//         const files = '../../../../../../files';
//         const settlementDetails = decode(settlement.settlementDetails).split('\\').slice(0, -1);
//         await execSync(`rm -rf ${path.join.apply(null, [__dirname, files, ...settlementDetails])}`);
//     } catch (error) {
//         log('---------------------------------------------------')
//         console.log(error)
//     }
// }

// ----------------------------------------------------------------------------------------------------------------------------

/** 输出 添加 (INSERT) 字符串 */
function toInsert(value, affix) {
    const keys = [];
    const vals = [];

    for (let key in value) {
        keys.push(key);
        vals.push(typeof value[key] === 'string' ? `'${value[key]}'` : value[key])
    }

    for (let key in affix) {
        keys.push(key);
        vals.push(affix[key])
    }

    return `(${keys.join(',')}) VALUES (${vals.join(',')})`
}

/** 执行 sh 脚本 */
// function execSync(command) {
//     return new Promise(resolve => {
//         process.exec(command, resolve)
//     })
// }